﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PSI.Models;
using PSI.Helper;
using System.Text;

namespace PSI.Services {
    public class AccountTitleService:PSIBaseService {


        public Result AddItemAT(AccountTitle model) {

            //判断科目码是否正确

            //  if (model.ATCode.Substring(0, 4) != "6602") return new Result { Success = false, Messgae = "不是有效的科目码!" };


            var systemporp = new SystemPropService().GetItemByPoryName("科目分级");

            var sys = systemporp.PropValue.Split('-');

            var list = new List<int>();

            var tempnum=0;
            foreach (var item in sys) {
                tempnum+=int.Parse(item);
                list.Add(tempnum);
            }

            // list.RemoveAt(0);

            var tt = list.Where(a => a == model.ATCode.Length).ToList();

           if (tt.Count == 0) return new Result { Success = false, Messgae = "不是有效的科目码!" };

           //判断同分类中是否有相同的科目码
           var itembycategory = GetAddItem();

           var cc = itembycategory.Where(a => a.ATCategory == model.ATCategory && a.ATCode == model.ATCode).ToList();



            //如果不是初级科目判断上级科目是否存在

            var arryindex=list.IndexOf(model.ATCode.Length);

            if (arryindex > 1) {

                var par = list[arryindex - 1];

                var parentcode = model.ATCode.Substring(0, par);

                var isyou = itembycategory.Where(a => a.ATCode == parentcode && a.ATCategory == model.ATCategory).ToList();

                if (isyou.Count == 0) return new Result { Success = false, Messgae = "找不到科目码的上级记录！" };
           
            }

            if (model.IsLeaf != null) {

              var last = sys.Last();

              var max = model.ATCode.Length - int.Parse(last);

              if (max !=4) {

                  var nn = model.ATCode.Substring(0, max);

                  var isyou = itembycategory.Where(a => a.ATCode == nn && a.ATCategory == model.ATCategory).ToList();

                  if (isyou.Count == 0) return new Result { Success = false, Messgae = "找不到科目码的上级记录！" };
              }
            
            }

            if(string.IsNullOrEmpty(model.ATId))
            {
               
                if (cc.Count != 0) return new Result { Success = false, Messgae = "该类别中包含相同的科目码!" };

                var addstr = new StringBuilder("insert psi_account_title values (@id,@code,@name,@category,@isleaf,@bcid)");

                var p = CreateDbParameters();

                p.AddWithValue("id",Guid.NewGuid());
                p.AddWithValue("code", model.ATCode);
                p.AddWithValue("name", model.ATName);
                p.AddWithValue("category", model.ATCategory);
                p.AddWithValue("isleaf",model.IsLeaf==null?0:1);
                p.AddWithValue("bcid",model.BizCategoryId);

                var falg = Execute(addstr.ToString(), p);

                if (falg > 0)
                    return new Result { Success = true };
                else
                    return new Result { Success = false,Messgae="系统错误！添加失败！" };

            }
            else
            {


                if (model.IsLeaf != null) {

                    var child = GetAddItem().Where(a => a.ATCode.Contains(model.ATCode) && a.ATCode != model.ATCode && a.ATCategory == model.ATCategory).OrderBy(a => a.ATCode).ToList<AccountTitle>();

                    if (child.Count > 0) {

                        return new Result { Success = false, Messgae = "科目码存在子节点不允许为末级节点！" };
                    }
                
                }


                var update = new StringBuilder("update psi_account_title set account_title_code=@code,account_title_name=@name,account_title_category=@category,is_leaf=@isleaf,biz_category_bc_id=@bcid where account_title_id=@id");

                var p = CreateDbParameters();

                p.AddWithValue("id", model.ATId);
                p.AddWithValue("code", model.ATCode);
                p.AddWithValue("name", model.ATName);
                p.AddWithValue("category", model.ATCategory);
                p.AddWithValue("isleaf", model.IsLeaf == null ? 0 : 1);
                p.AddWithValue("bcid", model.BizCategoryId);

                var falg = Execute(update.ToString(), p);

                if (falg > 0)
                    return new Result { Success = true };
                else
                    return new Result { Success = false, Messgae = "系统错误！编辑失败！" };
                 
            }

            
        }

        public Result DeleteItem(AccountTitle model) {


            var child = GetAddItem().Where(a => a.ATCode.Contains(model.ATCode) && a.ATCode != model.ATCode).OrderBy(a => a.ATCode).ToList<AccountTitle>();

            if (child.Count > 0) {

                return new Result { Success = false, Messgae = "科目存在下级节点无法删除" };
            }


            var str = new StringBuilder("delete psi_account_title where account_title_id=@id");

            var p = CreateDbParameters();

            p.AddWithValue("id", model.ATId);


            var falg = Execute(str.ToString(), p);

            if (falg > 0)
                return new Result { Success = true };
            else
                return new Result { Success = false, Messgae = "系统错误！删除失败！" };

        
        }

        public List<AccountTitle> GetAddItem() {

            var result = new List<AccountTitle>();

            var str = new StringBuilder("select account_title_id,account_title_code,account_title_name,account_title_category,is_leaf,biz_category_bc_id from psi_account_title ");

            Query(str.ToString(), ready => {
                result.Add(new AccountTitle {

                    ATId=ready.GetString(0),
                    ATCode = ready.GetString(1),
                    ATName = ready.GetString(2),
                    ATCategory = ready.GetString(3),
                    IsLeaf= ready.GetString(4),
                    BizCategoryId=ready.GetString(5)
                });

            });

            return result;
        }

        public List<AccountTitle> GetTreeByName(string name) {

            var result = new List<AccountTitle>();

            var list = GetAddItem().Where(a => a.ATCategory == name).ToList<AccountTitle>();

            var systemporp = new SystemPropService().GetItemByPoryName("科目分级");

            var sys = systemporp.PropValue.Split('-');

            var lists = new List<int>();

            var tempnum = 0;
            foreach (var item in sys) {
                tempnum += int.Parse(item);
                lists.Add(tempnum);
            }

       //     lists.RemoveAt(0);
            //第一级 6002

            list = list.Where(a => a.ATCode.Length == lists.First()).OrderBy(a=>a.ATCode).ToList<AccountTitle>();

            foreach (var item in list) {

                var tempAT = new AccountTitle();

                tempAT.Id = item.ATId;
                tempAT.ATName = item.ATName;
                tempAT.ATCode = item.ATCode;
                tempAT.ATCategory = item.ATCategory;
                tempAT.IsLeaf = item.IsLeaf;
                tempAT.BizCategoryId = item.BizCategoryId;
                tempAT.Name =new BaseCodeMetadataService().GetItemSing(item.BizCategoryId).BasecodeName;

                //第二级 6602-01
                var child = GetAddItem().Where(a => a.ATCode.Contains(item.ATCode) && a.ATCode != item.ATCode&&a.ATCode.Length==lists.ElementAt(1)).OrderBy(a => a.ATCode).ToList<AccountTitle>();

                if (child.Count > 0) {
                    tempAT.Expandable = true;
                    tempAT.Expanded = true;
                    var tempat2 = new List<AccountTitle>();

                    foreach (var itemchild in child) {

                        var tempAT2 = new AccountTitle();
                        tempAT2.Id = itemchild.ATId;
                        tempAT2.ATName = itemchild.ATName;
                        tempAT2.ATCode = itemchild.ATCode;
                        tempAT2.ATCategory = itemchild.ATCategory;
                        tempAT2.IsLeaf = itemchild.IsLeaf;
                        tempAT2.BizCategoryId = itemchild.BizCategoryId;
                        tempAT2.Name = new BaseCodeMetadataService().GetItemSing(itemchild.BizCategoryId).BasecodeName;

                        //第三级 6602-01-01
                        var child1 = GetAddItem().Where(a => a.ATCode.Contains(itemchild.ATCode) && a.ATCode != itemchild.ATCode).OrderBy(a => a.ATCode).ToList<AccountTitle>();
                        if (child1.Count > 0) {
                            tempAT2.Expandable = true;
                            tempAT2.Expanded = true;
                            var tempat3 = new List<AccountTitle>();
                            foreach (var itemchild2 in child1) {

                                var tempAT3 = new AccountTitle();
                                tempAT3.Id = itemchild2.ATId;
                                tempAT3.ATName = itemchild2.ATName;
                                tempAT3.ATCode = itemchild2.ATCode;
                                tempAT3.ATCategory = itemchild2.ATCategory;
                                tempAT3.IsLeaf = itemchild2.IsLeaf;
                                tempAT3.BizCategoryId = itemchild2.BizCategoryId;
                                tempAT3.Name = new BaseCodeMetadataService().GetItemSing(itemchild2.BizCategoryId).BasecodeName;

                                //第四级 6602-01-01-01
                                var child2 = GetAddItem().Where(a => a.ATCode.Contains(itemchild2.ATCode) && a.ATCode != itemchild2.ATCode).OrderBy(a => a.ATCode).ToList<AccountTitle>();

                                if (child2.Count > 0) {
                                    //  tempAT3.Expandable = true;
                                    tempAT3.Expanded = true;

                                    var tempat4 = new List<AccountTitle>();

                                    foreach (var itemchild3 in child2) {

                                        var tempAT4 = new AccountTitle();
                                        tempAT4.Id = itemchild3.ATId;
                                        tempAT4.ATName = itemchild3.ATName;
                                        tempAT4.ATCode = itemchild3.ATCode;
                                        tempAT4.ATCategory = itemchild3.ATCategory;
                                        tempAT4.IsLeaf = itemchild3.IsLeaf;
                                        tempAT4.BizCategoryId = itemchild3.BizCategoryId;
                                        tempAT4.Name = new BaseCodeMetadataService().GetItemSing(itemchild3.BizCategoryId).BasecodeName;

                                        //第五级 6602-01-01-01-01

                                        var child3 = GetAddItem().Where(a => a.ATCode.Contains(itemchild3.ATCode) && a.ATCode != itemchild3.ATCode).OrderBy(a => a.ATCode).ToList<AccountTitle>();

                                        var tempat5 = new List<AccountTitle>();

                                        if (child3.Count > 0) {

                                            foreach (var itemchild4 in child3) {
                                                var tempAT5 = new AccountTitle();
                                                tempAT5.Id = itemchild4.ATId;
                                                tempAT5.ATName = itemchild4.ATName;
                                                tempAT5.ATCode = itemchild4.ATCode;
                                                tempAT5.ATCategory = itemchild4.ATCategory;
                                                tempAT5.IsLeaf = itemchild4.IsLeaf;
                                                tempAT5.BizCategoryId = itemchild4.BizCategoryId;
                                                tempAT5.Name = new BaseCodeMetadataService().GetItemSing(itemchild4.BizCategoryId).BasecodeName;
                                                tempAT5.Leaf = true;
                                                tempat5.Add(tempAT5);
                                            }
                                            tempAT4.Children = tempat5;
                                            tempAT4.Expanded = true;
                                        } else {
                                            tempAT4.Leaf = true;
                                        }
                                    }

                                    tempAT3.Children = tempat4;

                                } else {
                                    tempAT3.Leaf = true;
                                    
                                }


                                tempat3.Add(tempAT3);
                            }

                            tempAT2.Children = tempat3;

                        }
                        tempat2.Add(tempAT2);
                    }
                    tempAT.Children = tempat2;
                } else {
                    tempAT.Leaf = true;
        
                }
                result.Add(tempAT);
            }

            return result;
        }


    }
}